'''

Case Type： centos
Case Name： pid文件丢失，停止数据库
Create At:  2020/06/24
Owner    :  n@ningyali
Descption:  1.删除pid文件 2.默认stop关闭数据库连接 3.immediate模式强制关闭 4.还原

'''

import os
import sys
import unittest
import time
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *


class PidLost(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case077.py start------------')
        self.pid_file_path = os.path.join(macro.DB_INSTANCE_PATH, macro.PID_FILE_NAME)
        self.data_path = macro.DB_INSTANCE_PATH
        self.rootNode = Node()
        self.dbUserNode = Node(node='dbuser')
        self.com = Common()
        self.Constant = Constant()

    def test_pid_lost_stop_db(self):
        # 删除pid文件
        del_cmd = f'rm -rf {self.pid_file_path}'
        del_msg = self.dbUserNode.sh(del_cmd).result()
        self.log.info(del_msg)
        self.assertTrue(True)

        # 默认stop关闭数据库连接
        stop_msg = self.sh.executeGsctl('stop', self.Constant.GS_CTL_STOP_SUCCESS_MSG)
        self.log.info(stop_msg)
        self.assertFalse(stop_msg)

        # immediate模式强制关闭
        im_stop_msg = self.sh.executeGsctl('stop', self.Constant.GS_CTL_STOP_SUCCESS_MSG, '-m immediate')
        self.log.info(im_stop_msg)
        self.assertTrue(im_stop_msg)

    def tearDown(self):
        msg = self.com.kill_pid(self.rootNode, 9)
        self.assertEqual(msg, '')

        # 还原pid文件（启动数据库可生成该文件）
        is_started = self.sh.startDbCluster()
        self.assertTrue(is_started)

        self.log.info('-------------Opengauss_Reliability_Dbsys_Case077:用例执行完毕--------------')
